package com.tongtong.stsuserapi.service.login.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tongtong.stscommon.utils.checker.cellphoneChecker;
import com.tongtong.stsuserapi.dao.ManagerDao;
import com.tongtong.stsuserapi.dao.UserDao;
import com.tongtong.stsuserapi.pojo.Manager;
import com.tongtong.stsuserapi.pojo.User;
import com.tongtong.stsuserapi.pojo.authentication.LoginManager;
import com.tongtong.stsuserapi.pojo.authentication.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * 自定义UserDetailService类
 * 从数据库中获取用户信息，然后返回给SpringSecurity进行身份验证
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {

	@Autowired
	UserDao userDao;

	@Autowired
	ManagerDao managerDao;


	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

		if(!cellphoneChecker.isInvalidFormat(username))
		{
			LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
			queryWrapper.eq(User::getPhone,username);
			User user = userDao.selectOne(queryWrapper);

			if (Objects.isNull(user))
			{
				return null; // 直接向Provider返回null
			}

			// 设置权限

			List<String> list = new ArrayList<>(Arrays.asList("user"));

			// 把数据封装为UserDetails返回
			return new LoginUser(user, list);
		} else {
			LambdaQueryWrapper<Manager> queryWrapper = new LambdaQueryWrapper<>();
			queryWrapper.eq(Manager::getUsername,username);
			Manager manager = managerDao.selectOne(queryWrapper);

			if (Objects.isNull(manager))
			{
				return null; // 直接向Provider返回null
			}

			List<String> list = new ArrayList<>(Arrays.asList("manager"));

			// 把数据封装为UserDetails返回
			return new LoginManager(manager, list);
		}
	}
}